﻿using System.Xml;
using System.Windows.Forms;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Collections.Generic;

namespace OWASP.CodeReview.CodeCrawler.Functionalities.Reports.Templates {

    internal class xmlTemplate {

        /// <summary>
        /// Compiled XML - XSL Transformation with addiational input parameters
        /// </summary>
        /// <param name="xmlSourcePath">XML Source Path</param>
        /// <param name="xslSourcePath">XSL Source Path</param>
        /// <param name="reportOutputPath">File Output Path</param>
        /// <param name="additionalInputParameters">IDictionary Parameters Collection</param>
        public void DoXSLCompiledTransformation(string xmlSourcePath, 
                                                string xslSourcePath, 
                                                string reportOutputPath, 
                                                IDictionary<string, string> additionalInputParameters)
        {
            XPathDocument myXPathDoc            = new XPathDocument(xmlSourcePath);
            XslCompiledTransform myXslTrans     = new XslCompiledTransform(true);

            XsltArgumentList xslArg             = new XsltArgumentList();

            foreach (KeyValuePair<string,string> parameterObject in additionalInputParameters) {
                xslArg.AddParam(parameterObject.Key, string.Empty, parameterObject.Value);
            }

            myXslTrans.Load(xslSourcePath);

            XmlTextWriter xmlReportTextWriter    = new XmlTextWriter(reportOutputPath, null);
                            
                            myXslTrans.Transform(myXPathDoc, xslArg, xmlReportTextWriter);
                          xmlReportTextWriter.Close();
        }

        /// <summary>
        /// Compiled XML - XSL Transformation
        /// </summary>
        /// <param name="xmlSourcePath">XML Source Path</param>
        /// <param name="reportOutputPath"></param>
        /// <param name="xslSourcePath"></param>
        public void DoXSLCompiledTransformation(string xmlSourcePath, string xslSourcePath, string reportOutputPath) {
            XPathDocument myXPathDoc            = new XPathDocument(xmlSourcePath);
            XslCompiledTransform myXslTrans     = new XslCompiledTransform(false);

            XmlTextWriter xmlReportWriter   = new XmlTextWriter(reportOutputPath, null);

            try {
                
                myXslTrans.Load(xslSourcePath);
                
                myXslTrans.Transform(myXPathDoc, null, xmlReportWriter);
                xmlReportWriter.Close();
            }
            catch (System.Exception ex) {
                MessageBox.Show(ex.Message.ToString());
            }
            finally {
                xmlReportWriter.Close();    
            }

        }
    }
}